package com.wangjiacai.utils.web.validator;

import com.wangjiacai.utils.enums.ResultEnum;
import org.springframework.util.StringUtils;

import javax.validation.Constraint;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import javax.validation.Payload;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target({ElementType.METHOD, ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = Phone.PhoneValidator.class)
@SecureValid(errorMessageBy= Phone.PhoneErrorMessage.class)
public @interface Phone {

    String message() default "手机号格式不正确";

    ResultEnum result() default ResultEnum.ParamsInvalid;

    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};

    class PhoneValidator implements ConstraintValidator<Phone,String> {

        private String regex;

        @Override
        public void initialize(Phone phone) {
            regex = "^[1][345789][0-9]{9}$";
        }

        @Override
        public boolean isValid(String value, ConstraintValidatorContext constraintValidatorContext) {
            if(StringUtils.isEmpty(value)) return true;
            if (value.matches(regex)) return true;
            return false;
        }
    }
    class PhoneErrorMessage implements SecureValid.ErrorMessage<Phone> {
        @Override
        public ResultEnum resultEnum(Phone phone) {
            return phone.result();
        }
    }
}
